import React from 'react';
import videojs from 'video.js';
import 'video.js/dist/video-js.css';
import { message } from 'antd';
import { useDispatch } from 'react-redux';
import { updateProgress } from '../store/learningSlice';

const VideoPlayer = ({
  videoUrl,
  lessonId,
  courseId,
  onTimeUpdate,
  startTime = 0
}) => {
  const videoRef = React.useRef(null);
  const playerRef = React.useRef(null);
  const dispatch = useDispatch();

  React.useEffect(() => {
    if (!playerRef.current) {
      const videoElement = videoRef.current;
      if (!videoElement) return;

      playerRef.current = videojs(videoElement, {
        controls: true,
        fluid: true,
        sources: [{
          src: videoUrl,
          type: 'video/mp4'
        }]
      });
    }

    // 设置开始时间
    if (startTime > 0) {
      playerRef.current.currentTime(startTime);
    }

    // 监听播放进度
    playerRef.current.on('timeupdate', () => {
      const currentTime = playerRef.current.currentTime();
      const duration = playerRef.current.duration();
      const progress = (currentTime / duration) * 100;

      // 更新学习进度
      dispatch(updateProgress({
        courseId,
        lessonId,
        progress,
        currentTime,
        duration
      }));

      if (onTimeUpdate) {
        onTimeUpdate(currentTime, duration);
      }
    });

    // 错误处理
    playerRef.current.on('error', (error) => {
      message.error('视频加载失败，请稍后重试');
      console.error('Video Player Error:', error);
    });

    return () => {
      if (playerRef.current) {
        playerRef.current.dispose();
        playerRef.current = null;
      }
    };
  }, [videoUrl, courseId, lessonId, onTimeUpdate, startTime, dispatch]);

  return (
    <div style={{ width: '100%', maxWidth: '800px', margin: '0 auto' }}>
      <div data-vjs-player>
        <video
          ref={videoRef}
          className="video-js"
          style={{ width: '100%', height: 'auto' }}
        />
      </div>
    </div>
  );
};

export default VideoPlayer; 